import { Controller, Inject, Post, Body } from '@midwayjs/core'
import { AuthService } from '../../service/app/AuthService'
import { BaseController } from '../base.chontroller'

@Controller('/app/auth')
export class AuthController extends BaseController {
  @Inject()
  service!: AuthService

  // 注册
  @Post('/register')
  async register(@Body() data: {
    phone: string
    password: string
    role: number
    email?: string
    nickname?: string
  }) {
    if (!data?.phone || !data?.password || !data?.role) {
      return this.fail('缺少必要参数：phone、password、role')
    }

    try {
      const result = await this.service.register(data)
      return this.success(result, '注册成功')
    } catch (err: any) {
      return this.fail(err.message || '注册失败')
    }
  }

  // 登录
  @Post('/login')
  async login(@Body() data: {
    phone: string
    password: string
    role: number
  }) {
    if (!data?.phone || !data?.password || !data?.role) {
      return this.fail('缺少必要参数：phone、password、role')
    }

    try {
      const result = await this.service.login(data)
      return this.success(result, '登录成功')
    } catch (err: any) {
      return this.fail(err.message || '登录失败')
    }
  }

  // 登出
  @Post('/logout')
  async logout() {
    try {
      await this.service.logout()
      return this.success(null, '登出成功')
    } catch (err: any) {
      return this.fail(err.message || '登出失败')
    }
  }
}
